import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/home/index.dart';
import 'package:flutter_enjoy_plus/pages/mine/index.dart';
import 'package:flutter_enjoy_plus/utils/eventbus.dart';
import 'package:flutter_enjoy_plus/utils/logger.dart';
import 'package:flutter_enjoy_plus/utils/token.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "首页",
      "default": "tabs/home_default.png",
      "active": "assets/tabs/home_active.png"
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png"
    }
  ];

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
            // 仅有icon必传
            icon: Image.asset(
              item['default'],
              width: 32,
              height: 32,
            ),
            activeIcon: Image.asset(
              item['active'],
              width: 32,
              height: 32,
            ),
            label: item['title']),
      );
    }
    return items;
  }

  // 初始化本地token存储
  @override
  void initState() {
    // 推迟多少秒后执行，仍为异步任务
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    eventBus.on<LogoutEvent>().listen((event) {
      // logger.e('监听到了');
      Navigator.pushNamed(context, '/login');
    });

    //  implement initState
    super.initState();
  }

  // 当前下标
  int currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
          // tabbar控制的内容
          SafeArea(
              child: IndexedStack(
        // index控制内容切换
        index: currentIndex,
        // 切换的内容
        children: [HomePage(), MinePage(currentIndex:currentIndex)],
      )),
      // 底部tabbar样式
      bottomNavigationBar: BottomNavigationBar(
        items: barItemList(),
        type: BottomNavigationBarType.shifting,
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        // 点击切换
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }
}
